package com.qlylkj.lbk.ui.user.register

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.qlylkj.lbk.app.PreferenceHelper
import com.qlylkj.lbk.base.BaseViewModel
import com.qlylkj.lbk.model.api.ResultResponse
import com.qlylkj.lbk.model.repository.UserRepository

class RegisterViewModel : BaseViewModel() {

    private val _uiState = MutableLiveData<RegisterUiModel>()
    val uiState: LiveData<RegisterUiModel>
        get() = _uiState

    private val userRepository by lazy { UserRepository() }

    private fun emitUiState(
        showError: String? = null,
        loginSuccess: Boolean = false
    ) {
        val uiModel = RegisterUiModel(showError, loginSuccess)
        _uiState.value = uiModel
    }

    data class RegisterUiModel(
        val showError: String?,
        val loginSuccess: Boolean
    )

    fun register(username: String, password: String) {
        launch {
            val result = userRepository.register(username, password)
            if (result is ResultResponse.Success) {
                login(username, password)
            } else if (result is ResultResponse.Error) {
                emitUiState(showError = result.exception.message)
            }
        }
    }

    private fun login(username: String, password: String) {
        launch {
            val result = userRepository.login(username, password)
            if (result is ResultResponse.SuccessEntity) {
                PreferenceHelper.setUser(result.data)
                emitUiState(loginSuccess = true)
            } else if (result is ResultResponse.Error) {
                emitUiState(showError = result.exception.message)
            }
        }
    }

}